package com.xianyun.book.command.query;

import com.alibaba.cola.dto.PageResponse;
import com.xianyun.book.command.query.strategy.BookEsMultipleHandle;
import com.xianyun.book.command.query.strategy.BookMultipleHandle;
import com.xianyun.book.common.core.handle.HandleChain;
import com.xianyun.book.common.core.handle.HandleChainFactory;
import com.xianyun.book.common.core.handle.HandleParam;
import com.xianyun.book.convertor.BookConvertor;
import com.xianyun.book.dto.BookSearchQry;
import com.xianyun.book.dto.clientobject.BookInfoCO;
import com.xianyun.book.gatewayimpl.database.BookMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import java.util.Date;
import java.util.List;

/**
 * @author ytt
 */
@Slf4j
@Component
public class BookSearchQryExe {

    @Resource
    private BookMapper bookMapper;

    private final HandleChain<BookInfoCO,String> bookIChain = HandleChainFactory.buildHandleChain(
            BookEsMultipleHandle.class,
            BookMultipleHandle.class
    );

    /**
     * 考虑好怎么做一个组合的多重查询
     * 查询名称
     *  1、可以为书名
     *  2、可以为作者名称
     *  3、可以为书籍类型
     * @param qry
     * @return
     */
    public PageResponse<BookInfoCO> execute(BookSearchQry qry){
        if (qry.isNewPut()){
            log.info("首页条件查询: 条件:{},查询时间:{}","新上架",new Date());
            List<BookInfoCO> result = getBookInfoByNewTime();
            return PageResponse.of(result, result.size(), qry.getPageSize(), qry.getPageIndex());
        }else if (qry.isBestSelling()){
            log.info("首页条件查询: 条件:{},查询时间:{}","热销书籍",new Date());
            List<BookInfoCO> result = getBookInfoBySelling();
            return PageResponse.of(result, result.size(), qry.getPageSize(), qry.getPageIndex());
        } else {
            log.info("首页条件查询: 条件:{},查询时间:{}","菜单栏搜索",new Date());
            List<BookInfoCO> result = listBookListByCombine(qry.getSearchField());
            return PageResponse.of(result, result.size(), qry.getPageSize(), qry.getPageIndex());
        }
    }


    private List<BookInfoCO> listBookListByCombine(@NotEmpty String queryName){
        HandleParam<String> param = new HandleParam<>();
        param.setHandleData(queryName);
        return bookIChain.doListHandle(param);
    }

    /**
     * 根据上架时间获取书籍
     * @return 结果集
     */
    private List<BookInfoCO> getBookInfoByNewTime(){
        return BookConvertor.toDataTranslateList(bookMapper.selectBooksOrderByNewTime());
    }

    /**
     * 根据销量查询
     * @return 结果集
     */
    private List<BookInfoCO> getBookInfoBySelling(){
        return BookConvertor.toDataTranslateList(bookMapper.selectBooksOrderBySales());
    }


}
